package com.yzxb.erpsystem.service.impl;

import com.yzxb.erpsystem.entity.Supplier;
import com.yzxb.erpsystem.mapper.SupplierMapper;
import com.yzxb.erpsystem.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class SupplierServiceImpl implements SupplierService {
    
    @Autowired
    private SupplierMapper supplierMapper;
    
    @Override
    @Transactional
    public Supplier createSupplier(Supplier supplier) {
        // 非空校验
        if (supplier == null) {
            throw new IllegalArgumentException("供应商信息不能为空");
        }
        
        if (supplier.getSupplierCode() == null || supplier.getSupplierCode().trim().isEmpty()) {
            throw new IllegalArgumentException("供应商编码不能为空");
        }
        
        if (supplier.getSupplierName() == null || supplier.getSupplierName().trim().isEmpty()) {
            throw new IllegalArgumentException("供应商名称不能为空");
        }
        
        if (supplier.getContactPerson() == null || supplier.getContactPerson().trim().isEmpty()) {
            throw new IllegalArgumentException("联系人不能为空");
        }
        
        if (supplier.getContactPhone() == null || supplier.getContactPhone().trim().isEmpty()) {
            throw new IllegalArgumentException("联系电话不能为空");
        }
        
        // 检查供应商编码是否已存在
        if (supplierMapper.selectBySupplierCode(supplier.getSupplierCode()) != null) {
            throw new IllegalArgumentException("供应商编码已存在");
        }
        
        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        supplier.setCreatedTime(now);
        supplier.setUpdatedTime(now);
        
        // 设置默认状态为启用
        if (supplier.getStatus() == null || supplier.getStatus().trim().isEmpty()) {
            supplier.setStatus("ENABLED");
        }
        
        // 保存供应商
        int rows = supplierMapper.insert(supplier);
        if (rows != 1) {
            throw new RuntimeException("创建供应商失败");
        }
        
        return supplierMapper.selectById(supplier.getId());
    }
    
    @Override
    @Transactional
    public Supplier updateSupplier(Long id, Supplier supplier) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("供应商ID不能为空");
        }
        
        if (supplier == null) {
            throw new IllegalArgumentException("供应商信息不能为空");
        }
        
        // 查找现有供应商
        Supplier existingSupplier = supplierMapper.selectById(id);
        if (existingSupplier == null) {
            throw new IllegalArgumentException("供应商不存在");
        }
        
        // 更新供应商信息
        supplier.setId(id);
        supplier.setCreatedTime(existingSupplier.getCreatedTime());
        supplier.setUpdatedTime(LocalDateTime.now());
        
        // 检查供应商编码是否重复（排除当前供应商）
        Supplier supplierByCode = supplierMapper.selectBySupplierCode(supplier.getSupplierCode());
        if (supplierByCode != null && !supplierByCode.getId().equals(id)) {
            throw new IllegalArgumentException("供应商编码已存在");
        }
        
        // 更新供应商
        int rows = supplierMapper.update(supplier);
        if (rows != 1) {
            throw new RuntimeException("更新供应商失败");
        }
        
        return supplierMapper.selectById(id);
    }
    
    @Override
    @Transactional
    public void deleteSupplier(Long id) {
        // 参数校验
        if (id == null) {
            throw new IllegalArgumentException("供应商ID不能为空");
        }
        
        // 查找供应商
        Supplier supplier = supplierMapper.selectById(id);
        if (supplier == null) {
            throw new IllegalArgumentException("供应商不存在");
        }
        
        // 删除供应商
        int rows = supplierMapper.deleteById(id);
        if (rows != 1) {
            throw new RuntimeException("删除供应商失败");
        }
    }
    
    @Override
    public Optional<Supplier> getSupplierById(Long id) {
        if (id == null) {
            return Optional.empty();
        }
        
        Supplier supplier = supplierMapper.selectById(id);
        return Optional.ofNullable(supplier);
    }
    
    @Override
    public Optional<Supplier> getSupplierBySupplierCode(String supplierCode) {
        if (supplierCode == null || supplierCode.trim().isEmpty()) {
            return Optional.empty();
        }
        
        Supplier supplier = supplierMapper.selectBySupplierCode(supplierCode);
        return Optional.ofNullable(supplier);
    }
    
    @Override
    public List<Supplier> getAllSuppliers() {
        return supplierMapper.selectAll();
    }
    
    @Override
    public List<Supplier> getSuppliersByStatus(String status) {
        if (status == null || status.trim().isEmpty()) {
            return getAllSuppliers();
        }
        
        return supplierMapper.selectByStatus(status);
    }
    
    @Override
    @Transactional
    public Supplier enableSupplier(Long id) {
        Supplier supplier = getSupplierById(id)
                .orElseThrow(() -> new IllegalArgumentException("供应商不存在"));
        
        supplier.setStatus("ENABLED");
        supplier.setUpdatedTime(LocalDateTime.now());
        
        int rows = supplierMapper.update(supplier);
        if (rows != 1) {
            throw new RuntimeException("启用供应商失败");
        }
        
        return supplier;
    }
    
    @Override
    @Transactional
    public Supplier disableSupplier(Long id) {
        Supplier supplier = getSupplierById(id)
                .orElseThrow(() -> new IllegalArgumentException("供应商不存在"));
        
        supplier.setStatus("DISABLED");
        supplier.setUpdatedTime(LocalDateTime.now());
        
        int rows = supplierMapper.update(supplier);
        if (rows != 1) {
            throw new RuntimeException("禁用供应商失败");
        }
        
        return supplier;
    }
}